package com.WebMentorPro.system.controller;

import com.WebMentorPro.system.annotation.AuthCheck;
import com.WebMentorPro.system.common.BaseResponse;
import com.WebMentorPro.system.common.DeleteRequest;
import com.WebMentorPro.system.common.ErrorCode;
import com.WebMentorPro.system.common.ResultUtils;
import com.WebMentorPro.system.constant.UserConstant;
import com.WebMentorPro.system.exception.BusinessException;
import com.WebMentorPro.system.exception.ThrowUtils;
import com.WebMentorPro.system.model.dto.bookBorrow.BorrowAddRequest;
import com.WebMentorPro.system.model.dto.bookBorrow.BorrowQueryRequest;
import com.WebMentorPro.system.model.dto.bookBorrow.BorrowUpdateRequest;
import com.WebMentorPro.system.model.entity.BookBorrow;
import com.WebMentorPro.system.model.entity.Teacher;
import com.WebMentorPro.system.model.entity.User;
import com.WebMentorPro.system.model.vo.BookBorrowVO;
import com.WebMentorPro.system.model.vo.LoginUserVO;
import com.WebMentorPro.system.service.BookBorrowService;
import com.WebMentorPro.system.service.TeacherService;
import com.WebMentorPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 大咖阅读书籍借阅接口
 *
 * @author bianxinyao
 */
@RestController
@RequestMapping("/bookBorrow")
@Slf4j
@Api(tags = {"大咖阅读书籍借阅接口"})
public class BookBorrowController {

    @Resource
    private UserService userService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private BookBorrowService bookBorrowService;

    // region 登录相关

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户")
    @ApiModelProperty(value = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 获取当前登录异科导师
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login/teacher")
    @ApiOperation(value = "获取当前登录异科导师")
    public BaseResponse<Teacher> getLoginTeacher(HttpServletRequest request) {
        Teacher teacher = teacherService.getLoginTeacher(request);
        return ResultUtils.success(teacher);
    }

    // endregion

    // region 增删改查

    /**
     * 学生创建大咖阅读书籍借阅记录
     *
     * @param borrowAddRequest
     * @return
     */
    @PostMapping("/add/student")
    @ApiOperation(value = "学生创建大咖阅读书籍借阅记录")
    public BaseResponse<Long> addBookBorrowByStudent(@RequestBody BorrowAddRequest borrowAddRequest, HttpServletRequest request) {
        if (borrowAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        BookBorrow bookBorrow = new BookBorrow();
        Long id = userService.getLoginUser(request).getId();
        bookBorrow.setBorrowerId(id);
        bookBorrow.setBorrowTime(new Date());
        BeanUtils.copyProperties(borrowAddRequest, bookBorrow);
        boolean result = bookBorrowService.save(bookBorrow);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "学生创建大咖阅读书籍借阅记录");
        return ResultUtils.success(bookBorrow.getId());
    }

    /**
     * 老师创建大咖阅读书籍借阅记录（废弃）
     *
     * @param borrowAddRequest
     * @return
     */
    @PostMapping("/add/teacher")
    @ApiOperation(value = "老师创建大咖阅读书籍借阅记录（废弃）")
    public BaseResponse<Long> addBookBorrowByTeacher(@RequestBody BorrowAddRequest borrowAddRequest, HttpServletRequest request) {
        if (borrowAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        BookBorrow bookBorrow = new BookBorrow();
        Long id = teacherService.getLoginTeacher(request).getId();
        bookBorrow.setBorrowerId(id);
        BeanUtils.copyProperties(borrowAddRequest, bookBorrow);
        boolean result = bookBorrowService.save(bookBorrow);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "老师创建大咖阅读书籍借阅记录");
        return ResultUtils.success(bookBorrow.getId());
    }

    /**
     * 删除大咖阅读记录（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除大咖阅读记录（仅管理员）")
    public BaseResponse<Boolean> deleteBookBorrow(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        boolean result = bookBorrowService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除大咖阅读书籍借阅记录失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新大咖阅读书籍借阅记录
     *
     * @param borrowUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新大咖阅读书籍借阅记录")
    public BaseResponse<Boolean> updateBookBorrow(@RequestBody BorrowUpdateRequest borrowUpdateRequest, HttpServletRequest request) {
        if (borrowUpdateRequest == null || borrowUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        QueryWrapper<BookBorrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", borrowUpdateRequest.getId());
        BookBorrow one = bookBorrowService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "大咖阅读记录不存在");
        }

        one.setReturnTime(new Date());
        boolean result = bookBorrowService.updateById(one);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新大咖阅读书籍借阅记录失败");
        return ResultUtils.success(result);
    }

    /**
     * 获取全部的大咖阅读书籍借阅记录（仅管理员）
     *
     * @param borrowQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "获取全部的大咖阅读书籍借阅记录（仅管理员）")
    public BaseResponse<Page<BookBorrowVO>> getBookBorrow(@RequestBody BorrowQueryRequest borrowQueryRequest) {
        long current = borrowQueryRequest.getCurrent() == 0 ? 1 : borrowQueryRequest.getCurrent();
        long size = borrowQueryRequest.getPageSize() == 0 ? 10 : borrowQueryRequest.getPageSize();

        Page<BookBorrowVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<BookBorrowVO> expertReadingVOPage = bookBorrowService.getQueryWrapper(pageParam, borrowQueryRequest);

        return ResultUtils.success(expertReadingVOPage);
    }

    /**
     * 分页获取学生自己的获取全部的大咖阅读书籍借阅记录
     *
     * @param borrowQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/student")
    @ApiOperation(value = "分页获取学生自己的大咖阅读书籍借阅记录")
    public BaseResponse<Page<BookBorrowVO>> getBookBorrowByStudent(@RequestBody BorrowQueryRequest borrowQueryRequest, HttpServletRequest request) {
        // 学生id
        Long userId = userService.getLoginUser(request).getId();

        long current = borrowQueryRequest.getCurrent() == 0 ? 1 : borrowQueryRequest.getCurrent();
        long size = borrowQueryRequest.getPageSize() == 0 ? 10 : borrowQueryRequest.getPageSize();

        Page<BookBorrowVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<BookBorrowVO> expertReadingVOPage = bookBorrowService.getQueryByStudent(pageParam, borrowQueryRequest, userId);

        if (expertReadingVOPage == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询失败");
        }

        return ResultUtils.success(expertReadingVOPage);
    }

    /**
     * 分页获取老师的获取全部的大咖阅读书籍借阅记录
     *
     * @param borrowQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/teacher")
    @ApiOperation(value = "分页获取当前老师全部学生的大咖阅读书籍借阅记录(弃用)")
    public BaseResponse<Page<BookBorrowVO>> getBookBorrowByTeacher(@RequestBody BorrowQueryRequest borrowQueryRequest, HttpServletRequest request) {
        // 老师id
        Long teacherId = teacherService.getLoginTeacher(request).getId();

        long current = borrowQueryRequest.getCurrent() == 0 ? 1 : borrowQueryRequest.getCurrent();
        long size = borrowQueryRequest.getPageSize() == 0 ? 10 : borrowQueryRequest.getPageSize();

        Page<BookBorrowVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<BookBorrowVO> expertReadingVOPage = bookBorrowService.getQueryByMyStudent(pageParam, borrowQueryRequest, teacherId);
        if (expertReadingVOPage == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询失败");
        }
        return ResultUtils.success(expertReadingVOPage);
    }

    // endregion
}
